import requests
import time
import hmac
import base64
import hashlib
import json
# import frappe
import requests
import time
import hmac
import base64
import hashlib
import json
import os
import logging
from pathlib import Path
from datetime import datetime
import re


class GcClient:

    def __init__(self):
        #以下是沙箱环境
        self.host = "https://uat-oms.eminxing.com/public_open"
        self.appKey = "1e40adc162c6e98bcf3b00624bed0d99"
        self.appToken = "7013991264f611e98ea200e01b680258"
        self.sourceKey = "3tfly6uo"
        self.expiresIn = 0
        self.session = requests.Session()

    def _request(self, url, method, headers=None, params=None, data=None, files=None, timeout=30):
        try:
            full_url = self.host + url
            headers = headers or {}
            headers.update({
                "app-key": self.appKey,
                "app-token": self.appToken,
                "Accept": "application/json",
                "content-type": "application/json",
            })
            # frappe.logger().debug(f"GC API请求: {method} {full_url}")


            if method.lower() == "get":
                r = self.session.get(full_url, headers=headers, params=params, timeout=timeout)
            elif method.lower() == "post":
                if files:
                    r = self.session.post(full_url, headers=headers, files=files, data=data, timeout=timeout)
                else:
                    canonical_body = data
                    if canonical_body and isinstance(canonical_body, str):
                        canonical_body = canonical_body.encode("utf-8")
                    r = self.session.post(full_url, headers=headers, data=canonical_body, timeout=timeout)
            # 可扩展 put, delete

            try:
                r.raise_for_status()  # 检查HTTP状态码
            except requests.exceptions.HTTPError as http_err:
                response_text = None
                response_json = None
                if http_err.response is not None:
                    try:
                        response_text = http_err.response.text
                    except Exception:
                        response_text = None
                    try:
                        response_json = http_err.response.json()
                    except Exception:
                        response_json = None

                # frappe.logger().error(
                #     f"GC HTTP错误详情: status={getattr(http_err.response, 'status_code', 'unknown')} "
                #     f"url={full_url} response_text={response_text} response_json={response_json}"
                # )
                raise http_err

            response = r.json()

            # 检查业务错误码
            if not response.get('success', True):
                error_code = response.get('code', 'N/A')
                error_msg = response.get('msg', '未知错误')
                detailed_msg = f"GC API业务错误: {error_msg} (错误码: {error_code})"
                # frappe.logger().error(detailed_msg)

                # 创建更友好的异常信息
                friendly_exception = Exception(f"GC API调用失败: {error_msg}")
                friendly_exception.error_code = error_code
                friendly_exception.original_message = error_msg
                raise friendly_exception

            # frappe.logger().debug(f"GC API响应成功: {url}")
            return response

        except requests.exceptions.Timeout:
            error_msg = f"GC API请求超时: {url}"
            # frappe.logger().error(error_msg)
            raise Exception(error_msg)
        except requests.exceptions.ConnectionError:
            error_msg = f"GC API连接错误: {url}"
            # frappe.logger().error(error_msg)
            raise Exception(error_msg)
        except requests.exceptions.HTTPError as e:
            params_str = str(params) if params is not None else "None"
            data_str = str(data) if data is not None else "None"
            response_text = None
            response_json = None
            if e.response is not None:
                try:
                    response_text = e.response.text
                except Exception:
                    response_text = None
                try:
                    response_json = e.response.json()
                except Exception:
                    response_json = None

            error_msg = (
                f"GCAPI HTTP错误: {e} - {method} - {url} - {headers} - {params_str} - {data_str} "
                f"- response_text={response_text} - response_json={response_json}"
            )
            # frappe.logger().error(error_msg)
            raise Exception(error_msg)
        except json.JSONDecodeError:
            error_msg = f"GCAPI响应JSON解析错误: {url}"
            # frappe.logger().error(error_msg)
            raise Exception(error_msg)
        except Exception as e:
            error_msg = f"GCAPI请求异常: {str(e)} - {url}"
            # frappe.logger().error(error_msg)
            raise Exception(error_msg)

    # 下面皆为 API方法，参数同 TS代码
    def get_warehouse(self):
        url = "/base_data/get_warehouse"
        try:
            result = self._request(url, "post")
            return result
        except Exception as e:
            raise e

    def get_country(self):
        url = "/base_data/get_country"
        try:
            result = self._request(url, "post")
            return result
        except Exception as e:
            raise e

    def get_fba_return_warehouse(self):
        url = "/base_data/get_fba_return_warehouse"
        try:
            result = self._request(url, "post")
            return result
        except Exception as e:
            raise e

    def get_product_map_barcode_list(self, product_sku_list: list):
        url = "/base_data/get_product_map_barcode_list"
        try:
            result = self._request(url, "post", data={"product_sku_list": product_sku_list})
            return result
        except Exception as e:
            raise e
